﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Diagnostics;
using System.IO;
using System.ComponentModel;
using WebApplication2.EntityFrameWork;
using static LBCMS.EntityFrameWork.ClassExtraAttribute;
using System.ComponentModel.DataAnnotations;
using LBCMS.BLL;

namespace LBCMS.Controllers
{
    public class CodeController : Controller
    {
        // GET: Code
        public ActionResult Index()
        {
            ViewBag.list = GetClasses("LBCMS.EntityFrameWork.FrameModel");

            return View();
        }

        /// <summary>
        /// 选择数据库类型
        /// </summary>
        /// <returns></returns>
        public ActionResult Step1()
        {

            List<BLL.Field> fieldList = getFieldList(Request["c"]);
            ViewBag.fieldList = fieldList;
            return View();
        }

        public ActionResult Step2()
        {

            return View();
        }

        public ActionResult Step3()
        {

            return View();
        }

        public ActionResult Step4()
        {

            return View();
        }

        public ActionResult Step5()
        {

            return View();
        }

        public ActionResult Step6()
        {

            return View();
        }

        public string getClassFields(string className)
        {
            var retData = new DataCalss.retData<BLL.Field>();

            List<BLL.Field> fieldList = getFieldList(className);
            retData.count = fieldList.Count;
            retData.data = fieldList;
            retData.code = 0;

            return Helper.JsonHelper.toJson(retData);

        }

        static Dictionary<string, string> GetClasses(string nameSpace)
        {
            Assembly asm = Assembly.GetExecutingAssembly();

            List<string> namespacelist = new List<string>();
            Dictionary<string, string> classlist = new Dictionary<string, string>();

            foreach (Type type in asm.GetTypes())
            {
                if (type.Namespace == nameSpace)
                {
                    var pName = type.GetCustomAttribute<DisplayNameAttribute>();
                    classlist.Add(type.Name, pName == null ? "-未命名-" : pName.DisplayName);
                }

            }

            return classlist;
        }

        public string GenClassFile(string json)
        {
            BLL.TableInfo table = Helper.JsonHelper.toObj<TableInfo>(json);

            string classFilePath = Server.MapPath("~") + "\\EntityFrameWork\\FrameModel\\" + table.ClassName + ".cs";
            //如果已经生成这忽略
            if (System.IO.File.Exists(classFilePath))
            {
                return Helper.JsonHelper.toFailJson();
            }
            var c = new CodeTemplates.BLLTemplates.Model();
            c.table = table;
            var code = c.TransformText();
            new Helper.FileHelper().WriteToFile(classFilePath, code);
            new Helper.csprojHelper().GenModelCsproj(table.ClassName);
            return Helper.JsonHelper.toSuccessJson();
        }

        protected List<BLL.Field> getFieldList(string className)
        {
            List<BLL.Field> fieldList = new List<BLL.Field>();
            string nameSpace = "LBCMS.EntityFrameWork.FrameModel";
            Assembly asm = Assembly.GetExecutingAssembly();
            foreach (Type type in asm.GetTypes())
            {
                if (type.Namespace == nameSpace && type.Name == className)
                {
                    foreach (PropertyInfo info in type.GetProperties())
                    {
                        var pName = info.GetCustomAttribute<DisplayNameAttribute>();
                        var pDecimal = info.GetCustomAttribute<DecimalPrecisionAttribute>();
                        var pSearch = info.GetCustomAttribute<Search>();
                        var pCheckBoxList = info.GetCustomAttribute<CheckBoxList>();
                        var pRadioButtonList = info.GetCustomAttribute<RadioButtonList>();
                        var pDropDownList = info.GetCustomAttribute<DropDownList>();
                        var pOriginalCheckBoxList = info.GetCustomAttribute<OriginalCheckBoxList>();
                        var pTree = info.GetCustomAttribute<Tree>();
                        var pCodeName = info.GetCustomAttribute<CodeName>();
                        var pDatePicker = info.GetCustomAttribute<DatePicker>();
                        var pRequire = info.GetCustomAttribute<RequiredAttribute>();
                        var pMaxLength = info.GetCustomAttribute<MaxLengthAttribute>();
                        var pDefaultValue = info.GetCustomAttribute<DefaultValueAttribute>();
                        var pHidden = info.GetCustomAttribute<Hidden>();
                        var pInline = info.GetCustomAttribute<Inline>();
                        var pSwicher = info.GetCustomAttribute<Switcher>();
                        var pShowInList = info.GetCustomAttribute<ShowInList>();
                        var pTextAare = info.GetCustomAttribute<TextArea>();


                        BLL.Field field = new BLL.Field();
                        field.FieldDisplayName = (pName == null ? "-未命名-" : pName.DisplayName);
                        field.FieldName = info.Name;
                        field.isSearch = (pSearch == null ? false : true);
                        field.isInline = (pInline == null ? false : true);
                        field.isRequired = (pRequire == null ? false : true);
                        field.isHidden = (pHidden == null ? false : true);
                        field.showInList = (pShowInList == null ? false : true);

                        field.maxLength = (pMaxLength == null ? 0 : pMaxLength.Length);

                        field.DisplayType = "";
                        if (field.DisplayType == "")
                        {
                            field.DisplayType = (pRadioButtonList == null ? "" : "Radio");
                        }
                        if (field.DisplayType == "")
                        {
                            field.DisplayType = (pDropDownList == null ? "" : "DropDownList");
                        }
                        if (field.DisplayType == "")
                        {
                            field.DisplayType = (pCheckBoxList == null ? "" : "CheckBox");
                        }
                        if (field.DisplayType == "")
                        {
                            field.DisplayType = (pOriginalCheckBoxList == null ? "" : "OriginalCheckBox");
                        }
                        if (field.DisplayType == "")
                        {
                            field.DisplayType = (pTree == null ? "" : "Tree");
                        }
                        if (field.DisplayType == "")
                        {
                            field.DisplayType = (pDatePicker == null ? "" : "DatePicker");
                        }
                        if (field.DisplayType == "")
                        {
                            field.DisplayType = (pSwicher == null ? "" : "Switcher");
                        }
                        if (field.DisplayType == "")
                        {
                            field.DisplayType = (pTextAare == null ? "" : "TextArea");
                        }
                        if (info.PropertyType == typeof(DateTime))
                        {
                            field.DisplayType = "DatePicker";
                        }
                        if (field.DisplayType == "")
                        {
                            field.DisplayType = "TextBox";
                        }



                        field.CodeName = (pCodeName == null ? "" : pCodeName.iCodeName);


                        fieldList.Add(field);
                    }

                }

            }
            return fieldList;
        }

        public string genCode(string tableNames)
        {


            var tables = tableNames.TrimEnd(';').Split(';');
            foreach (var item in tables)
            {
                var className = item.Split('|')[0];
                var tableName = item.Split('|')[1];

                List<BLL.Field> fieldList = getFieldList(className);

                if (className != "")
                {
                    string controllersPath = Server.MapPath("~") + "\\Controllers";
                    string viewsllersPath = Server.MapPath("~") + "\\Views\\" + className;
                    if (!Directory.Exists(viewsllersPath))
                    {
                        Directory.CreateDirectory(viewsllersPath);
                    }
                    string DataPath = controllersPath + "\\" + className + "Controller.cs";

                    //如果已经生成这忽略
                    if (System.IO.File.Exists(DataPath))
                    {
                        return Helper.JsonHelper.toFailJson();
                    }

                    BLL.TableInfo table = new BLL.TableInfo();
                    table.TableName = tableName;
                    table.ClassName = className;
                    table.FieldList = fieldList;
                    var c = new CodeTemplates.BLLTemplates.Controller();
                    c.table = table;
                    var code = c.TransformText();
                    new Helper.FileHelper().WriteToFile(DataPath, code);

                    DataPath = viewsllersPath + "\\Index.cshtml";
                    var l = new CodeTemplates.BLLTemplates.List();
                    l.table = table;
                    code = l.TransformText();
                    new Helper.FileHelper().WriteToFile(DataPath, code);

                    DataPath = viewsllersPath + "\\Data.cshtml";
                    var d = new CodeTemplates.BLLTemplates.Data();
                    d.table = table;
                    code = d.TransformText();
                    new Helper.FileHelper().WriteToFile(DataPath, code);

                    new Helper.csprojHelper().GenCsproj(className);
                }
            }




            return Helper.JsonHelper.toSuccessJson();
        }

        public string test()
        {

            //new Helper.csprojHelper().GenCsproj();

            return Helper.JsonHelper.toSuccessJson();
        }

        public string getStatus()
        {
            return Helper.JsonHelper.toSuccessJson();
        }

        public string complie()
        {

            RunBat();
            return Helper.JsonHelper.toSuccessJson();
        }

        private void RunBat()
        {
            return;

            string batPath = Server.MapPath("~") + "\\complie.bat";
            string slnPath = Server.MapPath("~") + "\\..\\LBCMS.sln";

            System.Diagnostics.Process.Start(batPath, slnPath);





            Process pro = new Process();
            FileInfo file = new FileInfo(batPath);
            pro.StartInfo.WorkingDirectory = file.Directory.FullName;
            pro.StartInfo.FileName = batPath;
            pro.StartInfo.CreateNoWindow = false;
            pro.StartInfo.Arguments = string.Format(slnPath);
            pro.Start();
        }

    }
}